package com.tacc.tyun.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import com.github.pagehelper.StringUtil;
import com.tacc.tyun.base.BaseConstant;
import com.tacc.tyun.model.BaseMenu;
import com.tacc.tyun.model.MsgMenu;
import com.tacc.tyun.model.info.MsgMenuInfo;
import com.tacc.tyun.model.info.ReturnInfo;
import com.tacc.tyun.service.BaseMenuService;
import com.tacc.tyun.service.MsgMenuService;
import com.tacc.tyun.util.BaseUtil;
import com.tacc.tyun.util.DateUtil;
import com.tacc.tyun.util.TreeUtil;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.List;

/**
* 导航菜单
* @author congcong tao
* @date 2017/8/9 16:49
*/
@Controller
@RequestMapping("/msgMenu")
public class MsgMenuController extends BaseController{

    private static Logger LOGGER= LoggerFactory.getLogger(MsgMenuController.class);

    @Resource
    private BaseMenuService baseMenuService;
    @Resource
    private MsgMenuService msgMenuService;

    private MsgMenu msgMenu;
    private BaseMenu baseMenu;

    @RequestMapping("/listPage")
    public ModelAndView listPage(HttpServletRequest request, HttpServletResponse response, String menuid){
        return new ModelAndView("msg/msgMenuList").addObject("headTitle",acceptTitle(menuid,baseMenuService));
    }

    @RequestMapping("/tree")
    public ModelAndView msgMenuTree(String type){
        ModelAndView mv=new ModelAndView("msg/msgMenuTree");
        mv.addObject("type",type);
        return mv;
    }

    @RequestMapping(value = "/JsonList",method = RequestMethod.POST)
    @ResponseBody
    public JSONObject JsonList(MsgMenu msgMenu, PageInfo<MsgMenu> pageInfo, String menuType) throws UnsupportedEncodingException {
        int pageNum=(pageInfo.getPageNum()/pageInfo.getPageSize())+1;
        pageInfo.setPageNum(pageNum);
        msgMenu.setRemoveTag(BaseConstant.REMOVE_NO);
        msgMenu.setType(menuType);
        //如果查询子类需要将父类带入
        pageInfo=msgMenuService.pageInfo(msgMenu,pageInfo.getPageSize(),pageInfo.getPageNum());
        JSONObject jsonObject=new JSONObject();
        jsonObject.put("total",pageInfo.getTotal());
        if(pageInfo !=null && pageInfo.getList() !=null && pageInfo.getList().size() > 0){
            JSONObject row = null;
            JSONArray rows = new JSONArray();
            List<MsgMenu> msgMenusList=pageInfo.getList();

            TreeUtil treeUtil = new TreeUtil();

            //分类好
            List<MsgMenu> msgMenusLists = treeUtil.getChildMsgMenus(msgMenusList, BaseConstant.MSG_MENU_MAXID);
            List<MsgMenu> msgMenuOrder = treeUtil.getMsgMenuOrder(msgMenusLists);

            for(MsgMenu item:msgMenuOrder){
                row=new JSONObject();
                row.put("menuId",item.getMenuId());

                row.put("name",item.getName());
                row.put("grade",item.getGrade());
                row.put("url",item.getMsgUrl());
                row.put("menuParentId",item.getMenuParentId());
                row.put("createTime", DateUtil.DateToStr(item.getCreateTime(),DateUtil.DATE_TIME_PATTERN));

                row.put("Id",item.getMenuParentId());
                row.put("ParentId",item.getMenuParentId());
                rows.add(row);
            }
            jsonObject.put("rows",rows);
        }
        return jsonObject;
    }

    @RequestMapping(value = "/JsonList",method = RequestMethod.GET)
    @ResponseBody
    public JSONArray JsonList(String menuType) throws UnsupportedEncodingException {

        //如果查询子类需要将父类带入
        MsgMenu record=new MsgMenu();
        record.setRemoveTag(BaseConstant.REMOVE_NO);
        record.setType(menuType);
        List<MsgMenu> msgMenus = msgMenuService.select(record);
        JSONObject jsonObject=new JSONObject();
        JSONArray rows = new JSONArray();
        if(msgMenus !=null && msgMenus.size() > 0){
            JSONObject row = null;
            TreeUtil treeUtil = new TreeUtil();
            //分类好
            List<MsgMenu> msgMenusLists = treeUtil.getChildMsgMenus(msgMenus, BaseConstant.MSG_MENU_MAXID);
            List<MsgMenu> msgMenuOrder = treeUtil.getMsgMenuOrder(msgMenusLists);

            for(MsgMenu item:msgMenuOrder){
                row=new JSONObject();
                row.put("menuId",item.getMenuId());
                row.put("name",item.getName());
                row.put("grade",item.getGrade());
                row.put("url",item.getMsgUrl());
                row.put("menuParentId",item.getMenuParentId());
                row.put("createTime", DateUtil.DateToStr(item.getCreateTime(),DateUtil.DATE_TIME_PATTERN));

                row.put("Id",item.getMenuId());

                if (!StringUtils.equals(item.getMenuParentId(),"0")){
                    row.put("ParentId",item.getMenuParentId());
                }
                rows.add(row);
            }
        }
        String jsonStr=rows.toJSONString();
        System.out.print(rows.toJSONString());
        return rows;
    }

    @RequestMapping(value = "/SelectEntity",method = RequestMethod.GET)
    public ModelAndView SelectEntity(String menuId, String menuParentId, String type){
        ModelAndView view=new ModelAndView("msg/msgMenuUpdateOrSave");
        if (StringUtils.isNotEmpty(menuId)){
            MsgMenu msgMenu=(MsgMenu)msgMenuService.selectByPrimaryKey(menuId);
            view.addObject(msgMenu);
        }
        if(StringUtil.isNotEmpty(menuParentId)){
            msgMenu=new MsgMenu();
            msgMenu.setMenuParentId(menuParentId);
            view.addObject(msgMenu);
        }
        if (StringUtils.isNotEmpty(type)){
            view.addObject("type",type);
        }else {
            LOGGER.error("非正常路径进入！");
        }
        return view;
    }

    @RequestMapping(value = "/UpdateOrAddEntity",method = RequestMethod.POST)
    @ResponseBody
    public JSONObject UpdateOrAddEntity(MsgMenuInfo msgMenuInfo, HttpServletRequest request){
        ReturnInfo returnInfo=new ReturnInfo();
        JSONObject jsonObject=new JSONObject();

        if(StringUtils.isEmpty(msgMenuInfo.getMenuId())){
            msgMenu=new MsgMenu();
            msgMenu.setMenuId(BaseUtil.uId());

            //msgMenu.setCreator(acceptUserName(request));
            msgMenu.setCreateTime(new Date());
            msgMenu.setUpdateTime(msgMenu.getCreateTime());
            msgMenu.setRemoveTag(BaseConstant.REMOVE_NO);

            msgMenu.setName(msgMenuInfo.getName());
            msgMenu.setType(msgMenuInfo.getType());
            msgMenu.setMsgUrl(msgMenuInfo.getUrl());
            MsgMenu parentMenu=null;
            if (StringUtils.isNotEmpty(msgMenuInfo.getMenuParentId())){//是子节点
                //在此基础上加1
                parentMenu = msgMenuService.selectByPrimaryKey(msgMenuInfo.getMenuParentId());
                msgMenu.setMenuParentId(msgMenuInfo.getMenuParentId());
                //该节点刚新建肯定是子节点
                msgMenu.setLeafTag(BaseConstant.MSG_MENU_NOT_LEAFTAG);
                //此时父节点要改变状态
                parentMenu.setLeafTag(BaseConstant.MSG_MENU_IS_LEAFTAG);
                msgMenu.setGrade(parentMenu.getGrade()+1);
            }else{
                msgMenu.setMenuParentId(BaseConstant.MSG_MENU_MAXID);
                msgMenu.setLeafTag(BaseConstant.MSG_MENU_NOT_LEAFTAG);//新建则是子节点
                msgMenu.setGrade(BaseConstant.MSG_MENU_ONE);
            }
            int id=0;
            if (parentMenu!=null){
                id=msgMenuService.insertAndUpdateParent(msgMenu,parentMenu);
            }else{
                id=msgMenuService.insert(msgMenu);
            }

            if(id <= 0){
                returnInfo=new ReturnInfo(BaseConstant.FAIL,BaseConstant.DATABASE_ERROR_INSERT);
            }
        }else{
            msgMenu=msgMenuService.selectByPrimaryKey(msgMenuInfo.getMenuId());
            msgMenu.setName(msgMenuInfo.getName());
            msgMenu.setMsgUrl(msgMenuInfo.getUrl());
            msgMenu.setUpdateTime(new Date());
            int id=msgMenuService.updateByPrimaryKey(msgMenu);
            if(id <= 0){
                returnInfo=new ReturnInfo(BaseConstant.FAIL,BaseConstant.DATABASE_ERROR_UPDATE);
            }
        }
        jsonObject.put("returnInfo",returnInfo);
        return jsonObject;
    }

    /**
     * 根据ids批量删除
     * @param ids
     * @return
     */
    @RequestMapping(value = "/DeleteEntity",method = RequestMethod.DELETE)
    @ResponseBody
    public JSONObject deleteByIds(@RequestParam("ids")List<String> ids){
        ReturnInfo returnInfo=new ReturnInfo();
        JSONObject jsonObject=new JSONObject();
        if(ids==null || ids.size()<1){
            returnInfo=new ReturnInfo(BaseConstant.FAIL, BaseConstant.DATABASE_ERROR_CANSHU);
        }else {
            int info=msgMenuService.deleteMenuByIds(ids,BaseConstant.REMOVE_YES);//
            if (info==-1){
                LOGGER.error("删除失败");
                returnInfo=new ReturnInfo(BaseConstant.FAIL, BaseConstant.DATABASE_ERROR_DELETE);
            }
        }
        jsonObject.put("returnInfo",returnInfo);
        return jsonObject;
    }

    @RequestMapping(value = "/listEntity",method = RequestMethod.POST)
    @ResponseBody
    public List<MsgMenu> list(String type){
        MsgMenu record=new MsgMenu();
        record.setRemoveTag(BaseConstant.REMOVE_NO);
        record.setType(type);
        List<MsgMenu> msgMenuList = msgMenuService.select(record);
        return msgMenuList;
    }

}
